﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

public class RsaEncryptionHelper
{

    // 导出私钥为 PEM 格式 (PKCS#1)
    private static string ExportPrivateKeyPem(RSACryptoServiceProvider rsa)
    {
        var privateKey = rsa.ExportCspBlob(true);
        return "-----BEGIN RSA PRIVATE KEY-----\n" +
               Convert.ToBase64String(privateKey, Base64FormattingOptions.InsertLineBreaks) +
               "\n-----END RSA PRIVATE KEY-----";
    }

    // 导出公钥为 PEM 格式 (PKCS#1)
    private static string ExportPublicKeyPem(RSACryptoServiceProvider rsa)
    {
        var publicKey = rsa.ExportCspBlob(false);
        return "-----BEGIN PUBLIC KEY-----\n" +
               Convert.ToBase64String(publicKey, Base64FormattingOptions.InsertLineBreaks) +
               "\n-----END PUBLIC KEY-----";
    }

    // 从 PEM 格式导入公钥
    private static RSACryptoServiceProvider ImportPublicKeyPem(string pem)
    {
        var rsa = new RSACryptoServiceProvider();
        string base64 = ExtractBase64FromPem(pem, "PUBLIC KEY");
        byte[] publicKeyBytes = Convert.FromBase64String(base64);
        rsa.ImportCspBlob(publicKeyBytes);
        return rsa;
    }

    // 从 PEM 格式导入私钥
    private static RSACryptoServiceProvider ImportPrivateKeyPem(string pem)
    {
        var rsa = new RSACryptoServiceProvider();
        string base64 = ExtractBase64FromPem(pem, "PRIVATE KEY");
        byte[] privateKeyBytes = Convert.FromBase64String(base64);
        rsa.ImportCspBlob(privateKeyBytes);
        return rsa;
    }

    // 从 PEM 字符串中提取 Base64 内容
    private static string ExtractBase64FromPem(string pem, string keyType)
    {
        string header = $"-----BEGIN {keyType}-----";
        string footer = $"-----END {keyType}-----";

        int start = pem.IndexOf(header, StringComparison.Ordinal);
        if (start < 0) throw new ArgumentException("Invalid PEM format: missing header");

        start += header.Length;
        int end = pem.IndexOf(footer, start, StringComparison.Ordinal);
        if (end < 0) throw new ArgumentException("Invalid PEM format: missing footer");

        string base64 = pem.Substring(start, end - start);

        // 移除空白字符
        return Regex.Replace(base64, @"\s+", "");
    }

    // RSA 加密字符串 (使用 PEM 公钥)
    public static string EncryptString(string plainText, string publicKeyPem)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentException("Plain text cannot be null or empty");

        using (var rsa = ImportPublicKeyPem(publicKeyPem))
        {
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes = rsa.Encrypt(plainBytes, false);
            return Convert.ToBase64String(encryptedBytes);
        }
    }

    // RSA 解密字符串 (使用 PEM 私钥)
    public static string DecryptString(string encryptedText, string privateKeyPem)
    {
        if (string.IsNullOrEmpty(encryptedText))
            throw new ArgumentException("Encrypted text cannot be null or empty");

        using (var rsa = ImportPrivateKeyPem(privateKeyPem))
        {
            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            byte[] plainBytes = rsa.Decrypt(encryptedBytes, false);
            return Encoding.UTF8.GetString(plainBytes);
        }
    }
}